package net.tw.transactional2.controller;

import net.tw.transactional2.task.TaskCService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Hashtable;

@RestController
public class TaskController {

    @Autowired
    TaskCService taskCService;

    @Autowired
    @Qualifier("threadExchangeTable")
    Hashtable<Long, Object> threadExchangeTable;

    @RequestMapping("/transactional2")
    public String syncTaskC(@RequestParam("threadId") String threadId, @RequestParam("action") String action) {

        Long taskThreadId = Long.valueOf(threadId);
        Thread currentThread = Thread.currentThread();
        Long currentThreadId = currentThread.getId();

        if (!threadExchangeTable.containsKey(taskThreadId)) {
            return "线程[" + threadId + "]不存在";
        }

        Hashtable<String, Object> threadExchangeData = new Hashtable<>();
        threadExchangeData.put("thread_id", currentThreadId);
        threadExchangeData.put("action", action);

        threadExchangeTable.put(taskThreadId, threadExchangeData);
        taskCService.syncTaskC(Long.valueOf(threadId));

        String retMsg = null;
        synchronized (currentThread) {
            try {
                currentThread.wait();
                retMsg = threadExchangeTable.get(currentThreadId).toString();
            } catch (InterruptedException e) {
                retMsg = e.getMessage();
            }
        }

        threadExchangeTable.remove(currentThread);

        return retMsg;
    }
}
